<template>
	<oauth-loading></oauth-loading>
</template>

<script>
import Route from '@/utils/Route.js';
import Tools from '@/utils/Tools.js';
import oauthLoading from '@/components/oauth/loading.vue';
export default {
	components: { oauthLoading },
	data() {
		return {
			type: 'home',
			referee_id: '',
			authed: false
		};
	},
	onLoad(options) {
		this.type = options.type;
		this.referee_id = options.referee_id;
		this.wxappLogin();
	},
	onUnload() {
		uni.removeStorageSync('appUserDetail');
	},
	methods: {
		wxappLogin() {
			uni.getProvider({
				service: 'oauth',
				success: res => {
					const provider = res.provider[0];
					let code = '';
					uni.login({
						provider,
						success: res => {
							switch (provider) {
								case 'weixin':
									code = this.wxappLoginForWeixin(res);
									break;
								default:
									break;
							}
							this.$nextTick(() => {
								this.codeToAuthId(code, provider);
							});
						}
					});
				}
			});
		},
		oauthError(msg = '小程序授权登录失败，请使用帐号密码登录') {
			Tools.showError(msg, () => {
				Route.navigateBack();
			});
		},
		//微信小程序授权登录
		wxappLoginForWeixin(res) {
			if (res.errMsg == 'login:ok') {
				return res.code;
			} else {
				this.oauthError();
			}
		},
		//
		codeToAuthId(code, provider) {
			//获取前面授权的detail
			const appUserDetail = uni.getStorageSync('appUserDetail') || '';
			if (appUserDetail) {
				this.$post(
					this.$api.loginMP,
					{
						signature: appUserDetail.signature,
						encrypted_data: appUserDetail.encryptedData,
						iv: appUserDetail.iv,
						user_info: JSON.stringify(appUserDetail.userInfo),
						code,
						provider,
						referee_id: Tools.getSuperiorId()
					},
					res => {
						const bindStatus = res.data.code;
						const authId = res.data.id;
						const referee_id = res.data.referee_id;
						uni.setStorageSync('authId', authId);
						switch (this.type) {
							case 'login':
								this.codeForLogin(authId, bindStatus, referee_id);
								break;
							case 'home':
								this.mpToHome(authId);
								break;
							default:
								break;
						}
						console.log(res);
					},
					() => {
						console.log(111)
						this.oauthError();
					}
				);
			} else {
				this.oauthError();
			}
		},
		mpToHome(authId) {
			// Route.reLaunch();
			Tools.redirectToCurrentPage()
		},
		codeForLogin(authId, bindStatus, referee_id) {
			if (bindStatus == 1) {
				this.$get(
					this.$api.loginByThirdId,
					{ login_type: 'wxapp', id: authId },
					res => {
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('user_id', res.data.userInfo.user_id);
						uni.setStorageSync('referee_id', res.data.userInfo.code);
						Route.reLaunch();
					},
					() => {
						this.oauthError();
					},
					() => {
						this.authed = true;
					}
				);
			} else {
				Route.redirectTo({ url: '/pages/login/index?next=1&authId=' + authId + '&referee_id=' + referee_id });
			}
		}
	}
};
</script>

<style></style>
